<template>
  <el-card>
    <BasicTableForm
      ref="tableForm"
      :formColumns="formItemList"
      :dataSource="formData"
      :handleSearchForm="queryFormFn"
      :hasQueryPermission="false"
      :isScalingBtn="false"
      defaultExpandStatus
      @getFormData="getFormDataFn"
    />
    <skus-table
      showSelectCol
      showPagination
      :defaultMinWidth="120"
      :loading="tableInfo.loading"
      :columns="tableInfo.columns"
      :dataSource="tableInfo.list"
      :pagination="pagination"
      :total="pagination.total"
      :actionRender="renderActionBtnFn"
      :selectionChange="handleSelectionChange"
      :checkSelectable="checkSelectableFn"
      :pageSizes="[10, 20, 40, 200]"
      @pageChange="handlePageChange"
      @pageSizeSelect="handlePageSizeChange"
    >
      <template slot="content_context">
        <el-row type="flex">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-connection"
            :disabled="selectionList.length === 0"
            @click="handleBatchSetQualification"
            >批量配置资质</el-button
          >
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-delete"
            :loading="btnLoading.batchClear"
            :disabled="selectionList.length === 0"
            @click="handleBatchClearQualification"
            >批量清空资质</el-button
          >
        </el-row>
      </template>
    </skus-table>
    <!-- 设置资质弹框 -->
    <SetQualificationDialog
      :visible.sync="setQualification.visible"
      :dimensionKey="setQualification.dimensionKey"
      :handleAssociate="associateDialogAction"
      :handleCancel="cancelDialogAction"
      :handleQuery="queryDialogAction"
      actionBtnName="设置资质"
    />
    <!-- 批量设置资质弹框 -->
    <BatchSetQualificationDialog
      :visible.sync="batchSetQualification.visible"
      :dimensionKey="batchSetQualification.dimensionKey"
      :skuNos="batchSetQualification.skuNos"
      :handleBatchAssociate="batchAssociatedDialogAction"
      :handleAssociate="associateDialogAction"
      :handleQuery="queryDialogAction"
    />
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import BasicTableForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import SetQualificationDialog from '@/pages/commodity/components/SetQualificationDialog';
import BatchSetQualificationDialog from './components/BatchSetQualificationDialog';
import { tableColumns, formItemList } from './constants/indexPage';
import { isResponseSuccess } from '@/utils/bizUtils';
import { getInitFormData } from '@/utils/getUtils';
export default {
  components: {
    BasicTableForm,
    SkusTable,
    SetQualificationDialog,
    BatchSetQualificationDialog
  },
  data () {
    return {
      btnLoading: {
        batchClear: false
      },
      formData: getInitFormData(formItemList),
      formItemList: formItemList,
      tableInfo: {
        columns: tableColumns,
        list: [],
        loading: false
      },
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 10, // 每页条数
        total: 0 // 总条数
      },
      selectionList: [],
      setQualification: {
        visible: false,
        dimensionKey: 'uuid',
      },
      batchSetQualification: {
        visible: false,
        dimensionKey: 'uuid',
        skuNos: [],
      },
      isBatchSetFlag: false,
      currentRowData: {
        relUuid: '',
        relUuidKey: 'quaTypeSkuRelUuid', // 点击设置资质时，进入弹框的表格的uuid的所取字段名
        qualificationCate: '',
        qualificationCateKey: 'qualificationTypeNo'
      }
    };
  },
  // mounted () {
  //   this.$refs.tableForm.handleQueryForm();
  // },
  methods: {
    getFormDataFn (formData) {
      this.formData = formData;
    },
    /* 当前行表格数据是否禁用操作的方法 */
    currentRowIsDisabledFn (row) {
      return row[this.currentRowData.relUuidKey];
    },
    /* 表格勾选是否禁用判断方法 */
    checkSelectableFn ({ row }) {
      /**
       * @relUuidKey --- quaTypeSkuRelUuid
       * null，checkbox置灰
       * 非null，checkbox可选
      */
      return this.currentRowIsDisabledFn(row); // 返回值为true，勾选不可禁用，返回值为false，勾选禁用
    },
    /* 操作栏按钮渲染方法 */
    renderActionBtnFn (h, { row }) {
      return (<div class="table-action">
        {<el-button
          size="mini"
          type="text"
          disabled={!this.currentRowIsDisabledFn(row)}
          onClick={() => this.handleSetQualification(row)}
        >设置资质</el-button>}
      </div>);
    },
    getParamsFn (source, isOmit) {
      let paramsOmit = isOmit
        ? _.omit(source, [
          'qualificationName',
          'qualificationType',
          'supplyUuid',
          'supplyName',
          'isMaintain'
        ])
        : source;
      let searchParam = [];
      for (var key in paramsOmit) {
        searchParam.push(
          {
            name: key,
            value: paramsOmit[key]
          },
          {
            name: `${key}_q`,
            value: 'Like'
          }
        );
      }
      return searchParam;
    },
    /* 表单查询 */
    queryFormFn () {
      this.pagination.nowPage = 1;
      this.handleGetTableData();
    },
    /* 加载表格数据事件 */
    handleGetTableData () {
      const data = {
        nowPage: this.pagination.pageNum,
        pageShow: this.pagination.pageSize,
        ...this.formData,
      };
      this.getTableDataAction(data).then((res) => {
        this.tableInfo.list = res.results;
        this.pagination.total = res.totalNum;
      });
    },
    /* 获取表格数据action */
    async getTableDataAction (data) {
      const url = '/sysback/batchMaintainQua/getSkuQuaPager';
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, 'post', data);
        this.tableInfo.loading = false;
        if (!isResponseSuccess(res)) { return false; }
        return res.retData;
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    /* 表格数据勾选或勾选取消方法 */
    handleSelectionChange (list) {
      this.selectionList = list;
    },
    /* 改变页码事件 */
    handlePageChange (currentPage) {
      this.pagination.pageNum = currentPage;
      this.handleGetTableData(); // 重新加载表格数据
    },
    /* 改变当前页条数大小事件 */
    handlePageSizeChange (pageSize) {
      this.pagination.pageSize = pageSize;
      if (this.tableInfo.list.length === 0) {
        return false;
      }
      this.handleGetTableData(); // 重新加载表格数据
    },
    /* 设置资质弹框 */
    handleSetQualification (row) {
      const curBtnId = getBtnsId('设置资质');
      sessionStorage.setItem('buttonId', curBtnId);
      const { relUuidKey, qualificationCateKey } = this.currentRowData;
      this.currentRowData.relUuid = row[relUuidKey];
      this.currentRowData.qualificationCate = row[qualificationCateKey];
      this.isBatchSetFlag = false;
      this.setQualification.visible = true;
    },
    /* 获取设置资质弹框关联入参方法 */
    getSingleAssociateParamsFn (row) {
      return {
        data: {
          relUuid: this.currentRowData.relUuid,
          qualificationUuids: row[this.setQualification.dimensionKey]
        },
        url: '/sysback/qualificationskuqualificationrel/createRelate',
        isQs: true
      }
    },
    /* 获取批量设置资质弹框关联入参方法 */
    getBatchAssociateParamsFn (source) {
      let quaUuids = [source.qualificationUuid];
      if (_.isArray(source)) {
        quaUuids = source.map(item => item.qualificationUuid);
      }
      return {
        data: {
          skuNos: this.batchSetQualification.skuNos,
          quaUuids,
          enumTempProduct: this.formData.enumTempProduct,
        },
        url: '/sysback/batchMaintainQua/batchBinding',
        isQs: false
      }
    },
    /* 关联action请求 */
    async associateDialogAction (row) {
      const { data, url, isQs } = this.isBatchSetFlag
        ? this.getBatchAssociateParamsFn(row)
        : this.getSingleAssociateParamsFn(row);
      const res = await ApiRequest(url, 'post', data, isQs);
      if (res.retStatus !== '1') { return false; }
      return true;
    },
    /* 取消action请求 */
    async cancelDialogAction (row) {
      const data = {
        relUuid: this.currentRowData.relUuid,
        qualificationUuids: row[this.setQualification.dimensionKey]
      };
      const url = '/sysback/qualificationskuqualificationrel/deleteRelate';
      const res = await ApiRequest(url, 'post', data, true);
      if (res.retStatus !== '1') { return false; }
      return true;
    },
    /* 批量关联action请求 */
    async batchAssociatedDialogAction (selectableList) {
      const { data, url } = this.getBatchAssociateParamsFn(selectableList);
      const res = await ApiRequest(url, 'post', data);
      if (res.retStatus !== '1') { return false; }
      return true;
    },
    /* 获取设置资质弹框查询入参方法 */
    getSingleSetActionParamsFn ({ params, formData, tabsStatus }) {
      const { relUuid, qualificationCate } = this.currentRowData;
      const url = {
        firstTab: `/sysback/qualification/getNotRelByCondition?relUuid=${relUuid}`,
        secondTab: `/sysback/qualification/getRelByCondition?relUuid=${relUuid}`
      };
      const { pagination, sort } = params;
      const searchParam = [
        ...this.getParamsFn(formData),
        { name: 'qualificationCate', value: qualificationCate },
        { name: 'qualificationCate_q', value: 'EQ' },
      ];
      const singleSetParams = {
        ...pagination,
        ...sort,
        searchParam: JSON.stringify(searchParam)
      };
      return {
        url: url[tabsStatus] || '',
        data: singleSetParams
      };
    },
    /* 获取批量设置资质弹框查询入参方法 */
    getBatchSetActionParamsFn ({ params, formData }) {
      const url = '/sysback/batchMaintainQua/getQuaPager';
      const { pagination } = params;
      const batchSetParams = {
        ...formData,
        ...pagination,
        skuNos: this.batchSetQualification.skuNos,
        enumTempProduct: this.formData.enumTempProduct,
      };
      return {
        url,
        data: batchSetParams,
      };
    },
    /* 查询action请求 */
    async queryDialogAction ({ params, formData, tabsStatus }) {
      const { url, data } = this.isBatchSetFlag
        ? this.getBatchSetActionParamsFn({ params, formData })
        : this.getSingleSetActionParamsFn({ params, formData, tabsStatus });
      const res = await ApiRequest(url, 'post', data);
      if (!isResponseSuccess(res)) { return false; }
      return res.retData;
    },
    /* 批量设置资质事件 */
    handleBatchSetQualification () {
      if (this.selectionList.length === 0) {
        return this.$message.warning('请先勾选资质再进行设置');
      }
      const uniqList = _.uniqBy(this.selectionList, 'skuNo');
      const categoryUuidList = uniqList.map(item => item.categoryUuid);
      const categoryFlag = new Set(categoryUuidList).size !== 1;
      if (categoryFlag) {
        return this.$message.warning('SKU品类不一致');
      }
      this.batchSetQualification.skuNos = uniqList.map(item => item.skuNo);
      this.isBatchSetFlag = true;
      this.batchSetQualification.visible = true;
    },
    /* 获取批量清空资质action接口入参的方法 */
    getBatchUnbindingParamsFn () {
      let quaTypeQuaRelUuidList = [];
      const detailParamList = this.selectionList.reduce((value, item) => {
        if (item.quaTypeQuaRelUuid) {
          quaTypeQuaRelUuidList.push(item.quaTypeQuaRelUuid);
        }
        value.push({
          quaTypeSkuRelUuid: item.quaTypeSkuRelUuid,
          quaTypeQuaRelUuid: item.quaTypeQuaRelUuid
        });
        return value;
      }, []);
      if (quaTypeQuaRelUuidList.length !== this.selectionList.length) {
        this.$message.warning('不能勾选未维护的资质信息');
        return false;
      }
      return detailParamList;
    },
    /* 批量清空资质事件 */
    handleBatchClearQualification () {
      const detailParamList = this.getBatchUnbindingParamsFn();
      if (!detailParamList) { return false }
      const prompting = '批量清空后，所选择的商品的资质，将全部清空，确定要当前商品所关联的资质吗？';
      const title = '批量清空资质';
      this.btnLoading.batchClear = true;
      this.$confirm(prompting, title, {
        type: 'warning'
      }).then(() => {
        this.batchUnbindingAction({
          detailParamList,
          enumTempProduct: this.formData.enumTempProduct
        }).then(retData => {
          this.btnLoading.batchClear = false;
          if (!retData) {
            return false;
          }
          this.$message.success('批量清空资质成功');
          this.handleGetTableData();
        })
      }).catch(() => {
        this.btnLoading.batchClear = false;
      });
    },
    /* 批量解除绑定资质信息action请求 */
    async batchUnbindingAction (data) {
      const url = '/sysback/batchMaintainQua/batchUnbinding';
      const res = await ApiRequest(url, 'post', data);
      if (res.retStatus !== '1') { return false; }
      return true;
    },
  }
};
</script>
<style lang="less" scoped>
.action_bar_wrap {
  margin-bottom: 20px;
}
</style>
